/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.utils.SkuInfoUtil;
import org.springblade.modules.repair.vo.ElevatorPartsStructureRelationVO;
import org.springblade.modules.repair.mapper.ElevatorPartsStructureRelationMapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.repair.vo.part.shop.SkuDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 电梯配件结构关联配件信息表 服务实现类
 *
 * @author ysq
 * @since 2024-10-11
 */
@Service
public class ElevatorPartsStructureRelationServiceImpl extends BaseServiceImpl<ElevatorPartsStructureRelationMapper, ElevatorPartsStructureRelation> implements IElevatorPartsStructureRelationService {

	@Autowired
	private MaintainPartsWorkService maintainPartsWorkService;
	@Autowired
	private IElevatorPartsStructureTemplateRelationService elevatorPartsStructureTemplateRelationService;
	@Autowired
	private IPartsShopService partsShopService;
	@Autowired
	private MaintainPartsService maintainPartsService;
	@Autowired
	private MaintainPartsWorkSkuService partsWorkSkuService;

	@Override
	public IPage<ElevatorPartsStructureRelationVO> selectElevatorPartsStructureRelationPage(IPage<ElevatorPartsStructureRelationVO> page, ElevatorPartsStructureRelationVO elevatorPartsStructureRelation) {
		return page.setRecords(baseMapper.selectElevatorPartsStructureRelationPage(page, elevatorPartsStructureRelation));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void syncElevatorPartsStructureRelation(Long planId, Long elevatorId) {
		List<MaintainPartsWork> maintainPartsWorkList = maintainPartsWorkService.list(Wrappers.<MaintainPartsWork>lambdaQuery().eq(MaintainPartsWork::getPlanId, planId));
		maintainPartsWorkList.forEach(maintainPartsWork -> {
//			if (maintainPartsWork == null || maintainPartsWork.getCategoryId() == null || maintainPartsWork.getFinallySkuId() == null) {
//				return;
//			}

			// 根据逗号分隔，拿最后一个
			Long partsId = Long.valueOf(maintainPartsWork.getPartsId().split(",")[maintainPartsWork.getPartsId().split(",").length - 1]);
			MaintainParts maintainParts = maintainPartsService.getById(partsId);
			if (maintainParts == null || maintainParts.getStructureType() == 1) {
				return;
			}

			Long floorStandId = null;
			LambdaQueryWrapper<ElevatorPartsStructureRelation> wrapper = Wrappers.lambdaQuery(ElevatorPartsStructureRelation.class)
				.eq(ElevatorPartsStructureRelation::getElevatorId, elevatorId)
				.eq(ElevatorPartsStructureRelation::getPartsId, partsId);
			if (Func.isNotBlank(maintainPartsWork.getFloorStandIds())) {
				// 根据逗号分隔，拿最后一个
				floorStandId = Long.valueOf(maintainPartsWork.getFloorStandIds().split(",")[maintainPartsWork.getFloorStandIds().split(",").length - 1]);
				wrapper.eq(ElevatorPartsStructureRelation::getFloorStandTemplateId, floorStandId);
			} else {
				wrapper.isNull(ElevatorPartsStructureRelation::getFloorStandTemplateId);
			}

			List<ElevatorPartsStructureRelation> elevatorPartsStructureRelations =this.list(wrapper);
			if (elevatorPartsStructureRelations.stream().anyMatch(t -> Func.equalsSafe(t.getSkuId(), maintainPartsWork.getFinallySkuId()))) {
				return;
			}

			List<Long> workIds = new ArrayList<>();
			workIds.add(maintainPartsWork.getId());
			List<MaintainPartsWorkSku> skuList = partsWorkSkuService.selectListByWorkIds(workIds);
			Long finalFloorStandId = floorStandId;
			skuList.forEach(t -> {
				SkuDetailVO skuDetail = null;
				try {
					skuDetail = partsShopService.skuDetail(t.getFinallySkuId());
				} catch (Exception e) {
					return;
				}

				if (skuDetail != null) {
					String path;
					// 若配件未关联类目，先关联类目
					if (maintainParts.getCategoryId() == null) {
						try{
							path = partsShopService.getCategoryPathName(t.getCategoryId());
						}catch (Exception e) {
							return;
						}
						maintainParts.setCategoryId(t.getCategoryId());
						maintainParts.setCategoryInfo(path);
						maintainPartsService.updateById(maintainParts);
					}
					// 存入部件sku信息
					ElevatorPartsStructureRelation elevatorPartsStructureRelation = new ElevatorPartsStructureRelation();
					elevatorPartsStructureRelation.setElevatorId(elevatorId);
					elevatorPartsStructureRelation.setPartsId(partsId);
					elevatorPartsStructureRelation.setFloorStandTemplateId(finalFloorStandId);
					elevatorPartsStructureRelation.setSkuId(t.getFinallySkuId());
					elevatorPartsStructureRelation.setSkuInfo(SkuInfoUtil.attrHandle(skuDetail.getBrandName(), skuDetail.getSpuName(), skuDetail.getAttr()));
					this.save(elevatorPartsStructureRelation);
				}
			});
		});
	}

	@Override
	public List<Map<String, Object>> elevatorSkuList(Long elevatorId, Long partsId, Long floorStandTemplateId) {
		LambdaQueryWrapper<ElevatorPartsStructureRelation> wrapper = Wrappers.lambdaQuery(ElevatorPartsStructureRelation.class)
			.eq(ElevatorPartsStructureRelation::getElevatorId, elevatorId)
			.eq(ElevatorPartsStructureRelation::getPartsId, partsId);
		if (floorStandTemplateId != null) {
			wrapper.eq(ElevatorPartsStructureRelation::getFloorStandTemplateId, floorStandTemplateId);
		} else {
			wrapper.isNull(ElevatorPartsStructureRelation::getFloorStandTemplateId);
		}

		List<ElevatorPartsStructureRelation> elevatorPartsStructureRelations =this.list(wrapper);
		if (Func.isNull(elevatorPartsStructureRelations)) {
			return null;
		}

		List<Map<String, Object>> result = elevatorPartsStructureRelations.stream()
			.map(t -> {
				Map<String, Object> map = new HashMap<>(2);
				map.put("skuId", t.getSkuId());
				map.put("skuInfo", t.getSkuInfo());
				return map;
			}).collect(Collectors.toList());
		return result;
	}
}
